﻿using Microsoft.Win32;
using ShipsLog.Model;
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Linq;
using Verball;
using System.Timers;
using System.Threading.Tasks;

namespace Log
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Verbliser verbliser;
        private int counter = 0;
        public Timer progressTimer;
        public string[] DownloadMessage = { "D", "O", "W", "N", "L", "O", "A", "D", "I", "N", "G", " ", "P", "R", "O", "F", "I", "L", "E" };
        private ShipsModelControl modelControl;

        public MainWindow()
        {
            string workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"/ShipsLogV1";
            if (!Directory.Exists(workingDirectory))
            {
                Directory.CreateDirectory(workingDirectory);
                File.Copy(@"Grammar.xml", Path.Combine(workingDirectory, "Grammar.xml"));
                
            }
            File.Copy(@"Component.json1", Path.Combine(workingDirectory, "Component.json1"),true);
            Directory.SetCurrentDirectory(workingDirectory);
            SetBrowserFeatureControl();
            this.modelControl = new ShipsModelControl();
            this.modelControl.UserNotify += this.LoginError;
            Task.Run(() => this.modelControl.Init());
            InitializeComponent();
            
            this.DownloadText.ItemsSource = this.DownloadMessage;
            this.progressTimer = new Timer(1000);
            this.progressTimer.Enabled = false;
            this.progressTimer.AutoReset = true;
            this.progressTimer.Elapsed += progressTimer_Elapsed;
        }

        void progressTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
                {
                    if (timerEnabledButton.Content == "Stop")
                    {
                        if (this.counter < this.Slider1.Value)
                        {
                            this.counter++;
                        }
                        else
                        {
                            this.counter = 0;
                            this.modelControl.Update(false);
                        }

                        this.autoUpdateProgressBar.Value = this.counter;
                    }
                });
        }

        protected override void OnClosed(EventArgs e)
        {
            if (this.verbliser != null)
            {
                this.verbliser.Dispose();
            }

            if (this.modelControl != null)
            {
                this.modelControl.Dispose();
            }
            base.OnClosed(e);
        }

        private void SetBrowserFeatureControlKey(string feature, string appName, uint value)
        {
            using (var key = Registry.CurrentUser.CreateSubKey(
                String.Concat(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\", feature),
                RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                key.SetValue(appName, (UInt32)value, RegistryValueKind.DWord);
            }
        }

        private UInt32 GetBrowserEmulationMode()
        {
            int browserVersion = 7;
            using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer",
                RegistryKeyPermissionCheck.ReadSubTree,
                System.Security.AccessControl.RegistryRights.QueryValues))
            {
                var version = ieKey.GetValue("svcVersion");
                if (null == version)
                {
                    version = ieKey.GetValue("Version");
                    if (null == version)
                        throw new ApplicationException("Microsoft Internet Explorer is required!");
                }
                int.TryParse(version.ToString().Split('.')[0], out browserVersion);
            }

            UInt32 mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. Default value for Internet Explorer 11.
            switch (browserVersion)
            {
                case 7:
                    mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
                    break;
                case 8:
                    mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8
                    break;
                case 9:
                    mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
                    break;
                case 10:
                    mode = 10000; // Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 mode. Default value for Internet Explorer 10.
                    break;
                default:
                    // use IE11 mode by default
                    break;
            }

            return mode;
        }

        private void SetBrowserFeatureControl()
        {
            // http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx

            // FeatureControl settings are per-process
            var fileName = System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

            // make the control is not running inside Visual Studio Designer
            if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0)
                return;

            SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", fileName, GetBrowserEmulationMode()); // Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
            SetBrowserFeatureControlKey("FEATURE_AJAX_CONNECTIONEVENTS", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_DOMSTORAGE ", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_GPU_RENDERING ", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI  ", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_DISABLE_LEGACY_COMPRESSION", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_LOCALMACHINE_LOCKDOWN", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_OBJECT", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_SCRIPT", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_DISABLE_NAVIGATION_SOUNDS", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_SCRIPTURL_MITIGATION", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_SPELLCHECKING", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_STATUS_BAR_THROTTLING", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_TABBED_BROWSING", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_VALIDATE_NAVIGATE_URL", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_WEBOC_DOCUMENT_ZOOM", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_WEBOC_POPUPMANAGEMENT", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_WEBOC_MOVESIZECHILD", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_ADDON_MANAGEMENT", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_WEBSOCKET", fileName, 1);
            SetBrowserFeatureControlKey("FEATURE_WINDOW_RESTRICTIONS ", fileName, 0);
            SetBrowserFeatureControlKey("FEATURE_XMLHTTP", fileName, 1);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var conf = ConfigurationManager.GetSection("comapnionApp") as NameValueCollection;

            this.modelControl.PropertyChanged += modelControl_PropertyChanged;
            this.modelControl.TradeData.PropertyChanged += TradeData_PropertyChanged;
            this.verbliser = new Verbliser(this.modelControl);
            this.SetCommader();
            this.SetStations();
            this.SetRecomendations();
            this.SetHistory();
            this.SetImage();
            if (this.modelControl.Ship != null)
            {
                this.webBrowser1.Navigate(@"http:\\coriolis.io/outfit/" + this.modelControl.Ship.ToString());
            }
        }

        private void SetImage()
        {
            string imageFolder = this.modelControl.ImageFolder;
            foreach (var file in new DirectoryInfo(imageFolder).GetFiles("*.bmp"))
            {

                string pngName = file.FullName.Substring(0, file.FullName.Length - 4) + ".png";
                if (!File.Exists(pngName))
                {
                    var bmp = System.Drawing.Bitmap.FromFile(file.FullName);
                    bmp.Save(pngName, System.Drawing.Imaging.ImageFormat.Png);
                    File.SetCreationTime(pngName, file.CreationTime);
                }
            }

            var lastPngNameList = new DirectoryInfo(imageFolder).GetFiles("*.png").OrderByDescending(o => o.CreationTime);
            if (lastPngNameList != null && lastPngNameList.Count() > 0)
            {
                string lastPngName = lastPngNameList.First().FullName;
                this.screenGrabImage.Source = new BitmapImage(new Uri(lastPngName));
                this.imageFileName.Text = lastPngName;
                
            }            
        }

        private void SetHistory()
        {
            if(this.modelControl.History != null)
            {                
                this.dateTimeAxis.Minimum = ClientBackBone.EDDN.Commander.firstData;
                this.dateTimeAxis.Maximum = ClientBackBone.EDDN.Commander.lastData;
                this.cashAxis.Minimum = ClientBackBone.EDDN.Commander.minCredits;
                this.cashAxis.Maximum = ClientBackBone.EDDN.Commander.maxCredits;
                this.Dept.ItemsSource = this.modelControl.History.OnlyDiffernt((a,b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Ship.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Cargo.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Cash.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Dept.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Ship.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Cargo.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.Cash.ItemsSource = this.modelControl.History.OnlyDiffernt((a, b) => (a.StackedCashValue != b.StackedCashValue) && (a.shipValue != b.shipValue));
                this.dateTimeAxis.Minimum = ClientBackBone.EDDN.Commander.firstData;
                this.dateTimeAxis.Maximum = ClientBackBone.EDDN.Commander.lastData;
                this.cashAxis.Minimum = ClientBackBone.EDDN.Commander.minCredits;
                this.cashAxis.Maximum = ClientBackBone.EDDN.Commander.maxCredits;
            }
            
        }

        private void SetRecomendations()
        {
            if (this.modelControl.TradeData.Recommendations != null)
            {
                this.RecomendationList.ItemsSource = this.modelControl.TradeData.Recommendations;                
            }
        }

        private void SetStations()
        {
            if (this.modelControl.TradeData.Stations != null)
            {
                this.Stations1.ItemsSource = this.modelControl.TradeData.Stations;
                this.Stations2.ItemsSource = this.modelControl.TradeData.Stations;
            }
        }

        void TradeData_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
                {
                    switch (e.PropertyName)
                    {
                        case "Stations": this.SetStations();
                            break;
                        case "Recommendations": this.SetRecomendations();
                            break;

                    }
                });
        }

        void modelControl_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
                {
                    switch (e.PropertyName)
                    {
                        case "Commander":
                            this.SetCommader();
                            this.verbliser.UpdateSucessfull();
                            //this.AddHistory();
                            this.webBrowser1.Navigate(@"http:\\coriolis.io/outfit/" + this.modelControl.Ship.ToString());
                            break;
                        case "IsUpdating":
                            this.DownloadProgress.IsIndeterminate = this.modelControl.IsUpdating;
                            break;
                        case "ScreenGrab":
                            this.SetImage();
                            break;
                        case "MenueMode":
                            this.SetMenue();
                            break;
                    }
                });
        }

        private void AddHistory()
        {
            this.Dept.ItemsSource = this.modelControl.History;
            this.Ship.ItemsSource = this.modelControl.History;
            this.Cargo.ItemsSource = this.modelControl.History;
            this.Cash.ItemsSource = this.modelControl.History;
        }

        private void SetMenue()
        {
            this.Status.Visibility = System.Windows.Visibility.Hidden;
            this.ShipPage.Visibility = System.Windows.Visibility.Hidden;
            this.Comod.Visibility = System.Windows.Visibility.Hidden;
            this.recomend.Visibility = System.Windows.Visibility.Hidden;
            this.grabs.Visibility = System.Windows.Visibility.Hidden;
            this.settings.Visibility = System.Windows.Visibility.Hidden;
            switch (this.modelControl.MenueMode)
            {
                case 0:
                    this.Status.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 1:
                    this.ShipPage.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 2:
                    this.Comod.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 3:
                    this.recomend.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 4:
                    this.grabs.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 5:
                    this.settings.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }

        private void SetCommader()
        {
            if(this.modelControl.Commander != null)
            {
                this.DownloadProgress.IsIndeterminate = false;
                this.cmdName.Content = this.modelControl.Commander.name;
                this.cash.Content = this.modelControl.Commander.credits;
                this.combatRank.Rank = this.modelControl.Commander.rank.combat;
                this.combatRank.ToolTip = this.modelControl.Commander.rank.combat_rating;
                this.exploreRank.Rank = this.modelControl.Commander.rank.explore;
                this.exploreRank.ToolTip = this.modelControl.Commander.rank.explore_rating;
                this.cqcRank.Rank = this.modelControl.Commander.rank.cqc;
                this.cqcRank.ToolTip = this.modelControl.Commander.rank.cqc_rating;
                this.tradeRank.Rank = this.modelControl.Commander.rank.trade;
                this.tradeRank.ToolTip = this.modelControl.Commander.rank.trade_rating;
                this.federationRank.Value = this.modelControl.Commander.rank.federation;
                this.federationRank.ToolTip = this.modelControl.Commander.rank.federation_rating;
                this.alianceRank.Value = this.modelControl.Commander.rank.aliance;
                this.alianceRank.ToolTip = this.modelControl.Commander.rank.aliance_rating;
                this.empireRank.Value = this.modelControl.Commander.rank.empire;
                this.empireRank.ToolTip = this.modelControl.Commander.rank.empire_rating;
                this.legalRank.Value = this.modelControl.Commander.rank.crime;
                this.legalRank.ToolTip = this.modelControl.Commander.rank.crime_rating;
                this.serviceRank.Value = this.modelControl.Commander.rank.service;
                this.serviceRank.ToolTip = this.modelControl.Commander.rank.service_rating;
                this.powerPlay.Rank = this.modelControl.Commander.rank.power;
                this.powerPlay.ToolTip = this.modelControl.Commander.rank.power_rating;
            }

            this.SetHistory();
        }

        private void LoginError(object sender, EventArgs<string> e)
        {
            this.Dispatcher.Invoke(() =>
            {

                if (e.Args == "companion.username")
                {
                    var dia = new GetEmail();
                    dia.Owner = this;
                    if (!dia.ShowDialog().Value)
                    {
                        this.Close();
                    }
                }
                else if (e.Args == "companion.code")
                {
                    var dia = new GetCode();
                    dia.Owner = this;
                    if (!dia.ShowDialog().Value)
                    {
                        this.Close();
                    }
                }
                else
                {
                    if (MessageBox.Show("Looks like there is some issues with the server, do you want to continue?", e.Args, MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        this.Close();
                    }
                    else
                    {
                        this.modelControl.LoadFromOld();
                    }
                }
            });
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 0;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 1;
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 2;
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 3;
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 4;
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            this.modelControl.MenueMode = 5;
        }

        private void Grid_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ButtonState == System.Windows.Input.MouseButtonState.Pressed)
            {
                App.Current.MainWindow.DragMove();
            }
            else if(e.ClickCount > 1)
            {
                if (App.Current.MainWindow.WindowState == WindowState.Maximized)
                {
                    App.Current.MainWindow.WindowState = WindowState.Normal;
                }
                else if (App.Current.MainWindow.WindowState == WindowState.Normal)
                {
                    App.Current.MainWindow.WindowState = WindowState.Maximized;
                }
            }
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            if (timerEnabledButton.Content == "Start")
            {
                autoUpdateProgressBar.Value = 0;
                progressTimer.Enabled = true;
                progressTimer.Start();
                timerEnabledButton.Content = "Stop";
            }
            else
            {
                progressTimer.Enabled = false;
                progressTimer.Stop();
                autoUpdateProgressBar.Value = 0;
                timerEnabledButton.Content = "Start";
            }
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            this.modelControl.ForgetMe();
        }

        private void Stations1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var x = Stations1.Items[Stations1.SelectedIndex] as ClientBackBone.EDDN.Station;
            this.Comodities1.ItemsSource = x.Comodities.Values;
        }

        private void Stations2_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var x = Stations2.Items[Stations2.SelectedIndex] as ClientBackBone.EDDN.Station;
            this.Comodities2.ItemsSource = x.Comodities.Values;
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            this.modelControl.NetWorkLogging(true);
        }

        private void RadioButton_Unchecked(object sender, RoutedEventArgs e)
        {
            this.modelControl.NetWorkLogging(false);
        }
    }
}